var router = require('express').Router();
var AV = require('leanengine');
var fs = require('fs');
var uuid = require('node-uuid');
var Todo = AV.Object.extend('Todo');
var common = require('../cloud/common');
var multiparty = require('multiparty');
var md5 = require('md5')
let redisManager = require('./redisManager/redisManager')
let moment = require('moment')
let momenttz = require('moment-timezone')
momenttz.locale('zh-cn');
var smTools = require('../queryFun/stortManagementTools');
var qiniu = require("qiniu")
var upload = require('../queryFun/fileuploads');
var qn = require('../qiniu/upload');
var apis = require( '../cloud/lib/apis' );
var message   = require( '../cloud/lib/message' );

//登录
router.post('/login', function (req, res, next) {
  var username = req.body.username;
  var password = req.body.password;

  // console.log(req.body,"-1--1-1-")
  AV.User.logIn(username, password).then(function (userObj) {
    res.saveCurrentUser(userObj);
    // console.log('req.currentUser',req.currentUser)
     var userInfo = {};
    userInfo.id = userObj.id;
    userInfo.username = userObj.get('username');

    userInfo.sessionToken = userObj._sessionToken
    var rs = common.getReturnArr("", 10000, "登陆成功", userInfo);
    res.json(rs);


  }, function (error) {
    console.log(error)
    var rs = common.getErrArr("账号或密码错误");
    res.json(rs)
  });
  // console.log("12334");

});
//退出登录
router.post("/logout", async function (req, res, next) {
  if (req.currentUser) {
    req.currentUser.logOut()
    res.clearCurrentUser()
  } else {
    console.log('req.currentUser不存在')
  }
  var rs = common.getReturnArr("", 10000, "退出成功", "");
  res.json(rs);
})

router.post('/phoneLogin', function (req, res, next) {
  // console.log(req.body)
  var phone = req.body.phone;
  var phoneCode = req.body.phoneCode;



  let userQuery = new AV.Query('_User')
  userQuery.equalTo('username', phone)


  let query = new AV.Query('UserRole')
  let role = new AV.Object.createWithoutData('RoleWX', '5a421672fe88c20063ddaa9e')
  query.equalTo('role', role)


  query.matchesQuery('userObj', userQuery)
  query.first().then(rr => {
    if (rr) {

      AV.User.signUpOrlogInWithMobilePhone(phone, phoneCode).then(function (userObj) {
        res.saveCurrentUser(userObj);
        var userInfo = {};
        userInfo.id = userObj.id;
        userInfo.username = userObj.get('username');

        userInfo.sessionToken = userObj._sessionToken
        var rs = common.getReturnArr("", 10000, "登陆成功", userInfo);
        res.json(rs);


      }).catch(error=>{
        console.log(error);
        var rs = common.getErrArr("账号或密码错误");
        res.json(rs)
      })
    }else {
      var rs = common.getErrArr("非代理用户，请向管理员申请代理！");
      res.json(rs)
    }
  })

});

//注册
router.post('/register', function (req, res, next) {
  // var RoleWxOId = "5a42fbf39f54540036a33bb9";
  var username = req.body.username;
  var password = req.body.password;
  var weChat = req.body.weChat;
  var name = req.body.name;
  var idCard = req.body.idCard;
  var phone = req.body.phone;
  var phoneCode = req.body.phoneCode;
  // AV.User.signUpOrlogInWithMobilePhone(phone, phoneCode).then(function (user) {
  // 成功
  var User = common.getEntity("_User");
  var user = new User();
  // console.log(user);
  user.set('username', username);
  user.set('password', password);
  user.set('repassword', password);
  user.set('weChat', weChat);
  user.set('name', name);
  user.set('idCard', idCard);
  user.set('mobilePhoneNumber', phone);
  user.save().then(result => {
    var userObj = AV.Object.createWithoutData("_User", result.id)

    var Account = common.getEntity("Account");
    var account = new Account();
    account.set("totalAmount", 0);
    account.set("userObj", userObj);
    account.set("userOId", result.id);
    account.set("deposit", 0);
    account.set("freezeMoney", 0);
    var accRs = account.save().then(acc => {
        return acc.id
      }, reject => console.log(reject)
    );

    // 5a4b4e92ee920a0045a4d5d5  游客
    var roleWX = AV.Object.createWithoutData("RoleWX", "5a4b4e92ee920a0045a4d5d5")

    var UserRole = common.getEntity("UserRole")

    var userRole = new UserRole()

    userRole.set("userObj", userObj)
    userRole.set("userOId", result.id)
    userRole.set("role", roleWX)
    userRole.set("roleState", -1)

    var relation = userRole.save().then(relation => {
        return relation.id
      }, reject => console.log(reject)
    );
    Promise.all([accRs, relation]).then(values => {
        // console.log(values)
        var rs = common.getReturnArr("", 10000, "注册成功", "");
        res.json(rs);
      }, err => {

        var rs = common.getErrArr("生成账户失败");
        res.json(rs);
      }
    );
  }, reject => {
    var rs = common.getErrArr("请输入验证码");
    res.json(rs);
  })

});

//获取店铺信息
async function getShopInfo(userOId){
  var query = new AV.Query('Shop_shop');
  // query.equalTo("status",'1');
  query.equalTo("userOId",userOId);
  return query.first().then(shopObj=>{
    return {
      shopOId:shopObj.id,
      shopName:shopObj.get('name')
    }
  }).catch(error=>{
    console.log(error)
  })
}
//获取商品列表
router.post('/getGoodsList',async function (req, res, next) {
  var shopInfo = await getShopInfo(req.currentUser.id)
  let shopOId = shopInfo.shopOId
  let page = req.body.page;
  let num = req.body.num;
  let objectId = req.body.goodsOId;
  let title = req.body.goodsName;
  let status = req.body.goodsStatus;
  let goodsTypeOId = req.body.goodsTypeOId;
  let isEdit = req.body.isEdit
  let postageModelOId = req.body.postageModelOId
  if (page == '' || page == undefined || page == null) {
    page = 1;
  } else {
    page = parseInt(page);
  }
  if (num == '' || num == undefined || num == null) {
    num = 10
  } else {
    num = parseInt(num)
  }
  var query = new AV.Query('Shop_goods');

  if (shopOId != "" && shopOId != undefined && shopOId != null) {
    query.equalTo("shopOId", shopOId);
  }
  if (objectId != "" && objectId != undefined && objectId != null) {
    query.equalTo("objectId", objectId);
  }
  if (title != "" && title != undefined && title != null) {
    query.contains("title", title);
  }
  if (goodsTypeOId != "" && goodsTypeOId != undefined && goodsTypeOId != null) {
    query.equalTo("shop_good_type_OId", goodsTypeOId);
  }
  if (status != "" && status != undefined && status != null) {
    query.equalTo("status", Number(status));
  } else {
    if (!objectId){
      query.notEqualTo("status", Number(-1))
    }
  }
  if (postageModelOId != "" && postageModelOId != undefined && postageModelOId != null) {
    query.equalTo("postageModelOId", postageModelOId);
  }
  query.skip((page - 1) * num);
  query.limit(num);
  query.include('shopObj');
  query.include('postageModelObj');
  query.include('shop_good_type_Obj');
  query.include('shopGoodsTypeParentObj');
  query.descending('createdAt');
  query.find().then(function (result) {
      query.count().then(async function (count) {
        var obj = {};
        var data = [];
        var qn = 'http://tribemedia.aladada.com/';
        // var picOIdArr=[];
        for (var i = 0; i < result.length; i++) {
          var temObj = {};
          temObj["objectId"] = result[i].get("objectId");
          temObj["goodsUrl"] = "https://health.aladada.com/goods/info?id="+result[i].get("objectId")+"&uId="+req.currentUser.id+"&tId="
          temObj["recommend"] = result[i].get("recommend") ? result[i].get("recommend") : '';//店长推荐
          temObj["groupBuying"] = result[i].get("groupBuying");//能否团购s
          temObj["promotePrice"] = result[i].get("promotePrice");//推广佣金
          temObj["shopName"] = result[i].get("shopObj") ? result[i].get("shopObj").get("name") : "";
          temObj["groupPrice"] = result[i].get("groupPrice");
          temObj["saleNums"] = result[i].get("saleNums");//销量
          temObj["title"] = result[i].get("title");//名称
          temObj["originalPrice"] = result[i].get("originalPrice");//原价
          temObj["status"] = result[i].get("status");//-1删除 0下架 1上架
          temObj["freePost"] = result[i].get("freePost");//包邮
          temObj["shopOId"] = result[i].get("shopOId");//店铺Id
          temObj["describe"] = result[i].get("describe");//描述
          temObj["discount"] = result[i].get("discount");//折扣
          temObj["price"] = result[i].get("price");//价格
          temObj["customize"] = result[i].get("customize");//订制 1可以 -1不可以
          temObj["stock"] = result[i].get("stock");//库存
          temObj["weight"] = result[i].get("weight");//商品重量
          temObj["postageModelOId"] = result[i].get("postageModelOId");//运费模板ID
          temObj["postageModelName"] = result[i].get("postageModelObj")?result[i].get("postageModelObj").get('name'):'';//运费模板名称
          let parentGoodsTypeName = result[i].get('shopGoodsTypeParentObj') ? result[i].get('shopGoodsTypeParentObj').get('name') : '';
          let goodsTypeName = result[i].get('shop_good_type_Obj') ? result[i].get('shop_good_type_Obj').get('name') : '';
          if (parentGoodsTypeName != '' && goodsTypeName != ''){
            temObj['goodsType'] = parentGoodsTypeName + '/' + goodsTypeName;
          } else {
            // temObj['goodsType'] = parentGoodsTypeName;
            temObj['goodsType'] = goodsTypeName;
          }
          temObj["createdAt"] = moment(result[i].createdAt).format('YYYY年MM月DD日 HH:mm:ss');
          temObj["updatedAt"] = moment(result[i].updatedAt).format('YYYY年MM月DD日 HH:mm:ss');
          temObj["shopIcon"] = result[i].get("picName") ? qn + result[i].get("picName") : "";
          if (objectId && isEdit && isEdit == '1'){

            let goodsTypeOIdArr = []
            if (result[i].get("shopGoodsTypeParentOId")){
              goodsTypeOIdArr.push(result[i].get("shopGoodsTypeParentOId"))
            }
            if (result[i].get("shop_good_type_OId")){
              goodsTypeOIdArr.push(result[i].get("shop_good_type_OId"))
            }
            temObj["goodsTypeOIdArr"] = goodsTypeOIdArr
            if (result[i].get("picArray")){
              let picArray = []
              result[i].get("picArray").forEach(item=>{
                picArray.push(item.id)
              })
              let shopGoodsPicQuery = new AV.Query('Shop_goodsPic')
              shopGoodsPicQuery.containedIn('objectId',picArray)
              shopGoodsPicQuery.ascending('sortNum')
              await shopGoodsPicQuery.find().then(shopGoodsPics=>{
                var shopGoodsPicArray =[]
                shopGoodsPics.forEach(shopGoodsPic=>{
                  // let shopGoodsPicUrl = qn+shopGoodsPic.get('picName')+'?imageMogr2/thumbnail/640x/format/jpg/interlace/1/auto-orient'
                  let tempDic = {}
                  tempDic.picName = shopGoodsPic.get('picName')
                  tempDic.sortNum = shopGoodsPic.get('sortNum')
                  shopGoodsPicArray.push(tempDic)
                })
                temObj["shopGoodsPicArray"] = shopGoodsPicArray
              }).catch(error=>{
                console.log('error:',error)
              })
            } else {
              console.log('picArray不存在')
            }
            if (result[i].get("modelArray")){

              let modelArray = []
              result[i].get("modelArray").forEach(item=>{
                modelArray.push(item.id)
              })
              let shopGoodsModelQuery = new AV.Query('Shop_goods_model_stock')
              shopGoodsModelQuery.containedIn('objectId',modelArray)
              // shopGoodsModelQuery.ascending('sortNum')
              await shopGoodsModelQuery.find().then(shopGoodsModels=>{
                var shopGoodsModelsArray =[]
                shopGoodsModels.forEach(shopGoodsModel=>{
                  // let shopGoodsPicUrl = qn+shopGoodsPic.get('picName')+'?imageMogr2/thumbnail/640x/format/jpg/interlace/1/auto-orient'
                  let tempModelDic = {}
                  tempModelDic.stock = shopGoodsModel.get('stock')
                  tempModelDic.model = shopGoodsModel.get('model')
                  shopGoodsModelsArray.push(tempModelDic)
                })
                temObj["modelStork"] = shopGoodsModelsArray
              }).catch(error=>{
                console.log('shopGoodsModelsArrayError:',error)
              })
            } else {
              console.log('modelArray不存在')
            }
          } else {
            // console.log('objectId不存在')
          }
          data.push(temObj);
        }
        obj.data = data;
        obj.total = count;
        obj.shopInfo = shopInfo;

        res.json(common.getReturnArr("OK", "10000", "商品列表获取成功！", obj));
      }).catch(err => {
        console.log(err);
      })
    }, function (error) {
      console.log(error);
      res.json(common.getErrArr(error.msg));
    }
  )
});

//获取七牛上传Token
router.post('/getQiniuUploadToken', function (req, res) {
  // console.log('getStoreManagementData')
  var config = qn.config;
  var options = {
    scope: config.Bucket,
    deleteAfterDays: 0,
  };
  var putPolicy = new qiniu.rs.PutPolicy(options);
  var mac = new qiniu.auth.digest.Mac(config.AccessKey, config.SecretKey);
  var token = putPolicy.uploadToken(mac);
  let data = {
      domain: config.Domain,
      uptoken: token,
  }
  // console.log(data)
  res.json(common.getReturnArr("OK", "10000", "七牛上传Token获取成功！", data));
});

//获取商品类型列表
router.post('/getGoodsTypeList', function (req, res) {
  // console.log('getGoodsTypeList')
  var query = new AV.Query('Shop_good_type');
  query.equalTo("fatherCode",'1');
  // query.doesNotExist('parentId')
  query.ascending("sortNum");
// query.addAscending('fatherCode');
  query.find().then(function (goodsTypes) {
    var parentObjArr = []
    var parentIDArr = []
    var childObjArr = []
    goodsTypes.map(item=>{
      let tempDic = {}
      let parentId = item.get('parentId') ? item.get('parentId'):''
      tempDic.value = item.id
      tempDic.label = item.get('name')
      if (parentId == ''){
        parentObjArr.push(tempDic)
        parentIDArr.push(item.id)
      } else {
        tempDic.pid = item.get('parentId')
        childObjArr.push(tempDic)
      }
    })
    childObjArr.map(childItem=> {
      let parentIndex = parentIDArr.indexOf(childItem.pid);
      if (!parentObjArr[parentIndex].children){
        parentObjArr[parentIndex].children = []
      }
      let childDic = {}
      childDic.value = childItem.value
      childDic.label = childItem.label
      parentObjArr[parentIndex].children.push(childDic)
    })
    res.json(common.getReturnArr("OK", "10000", "商品分类获取成功！", parentObjArr));
  }, function (error) {
    console.log(error);
    res.json(common.getErrArr(error.msg));
  })
});

//店铺商品更新
router.post('/shopGoodsUpdate',async function (req, res) {
  // console.log(req.body)
  req.body.sellerOId = req.currentUser.id
  var picArr = req.body.downUrl;
  var model = req.body.modelStork;
  var goodsId = await saveGoods(req);
  // console.log(goodsId)
  var picIdArr = await savePic(picArr, goodsId);
  // let delResult = await delModelForUpdateGoods()
  var modelArray = await saveModel(model, goodsId);
  var goods = AV.Object.createWithoutData("Shop_goods", goodsId);
  goods.set("picArray", picIdArr);
  goods.set("modelArray", modelArray);
  goods.save().then((result) => {
    res.json(common.getReturnArr("OK", "10000", "商品添加成功！", result.id));
  }, (reject) => {
    console.log(reject);
  })

  function saveGoods(req) {
    var objectId = req.body.objectId;
    if (objectId != "" && objectId != undefined && objectId != null) {
      var Shop = AV.Object.createWithoutData('Shop_goods', req.body.objectId);
    } else {
      var Shops = AV.Object.extend('Shop_goods');
      var Shop = new Shops();
      var shopObj = AV.Object.createWithoutData('Shop_shop', req.body.shopOId);
      var sellerObj = AV.Object.createWithoutData('_User', req.body.sellerOId);
      Shop.set('sellerOId', req.body.sellerOId);
      Shop.set('sellerObj', sellerObj);
      Shop.set('shopOId', req.body.shopOId);
      Shop.set('shopObj', shopObj);
    }
    // 修改属性
    Shop.set("picName", picArr[0]);
    Shop.set('title', req.body.title);
    Shop.set('promotePrice', Number(req.body.promotePrice));
    Shop.set('status', Number(req.body.status));
    Shop.set('groupBuying', Number(req.body.groupBuying));
    Shop.set('freePost', req.body.freePost);
    Shop.set('groupPrice', Number(req.body.groupPrice));
    Shop.set('saleNums', Number(req.body.saleNums));
    Shop.set('originalPrice', Number(req.body.originalPrice));
    Shop.set('price', Number(req.body.price));
    Shop.set('customize', Number(req.body.customize));
    Shop.set('discount', Number(req.body.discount));
    Shop.set('describe', req.body.describe);
    Shop.set('stock', Number(req.body.stock));
    Shop.set('weight', Number(req.body.weight));
    Shop.set('postageModelOId', req.body.postageModelOId);
    let postageModelObj = AV.Object.createWithoutData('PostageModel', req.body.postageModelOId);
    Shop.set('postageModelObj', postageModelObj);
    let shopGoodsTypeParentOId = req.body.goodsType.goodsTypePId
    let shop_good_type_OId = req.body.goodsType.goodsTypeCId
    if (shop_good_type_OId != "" && shop_good_type_OId != undefined && shop_good_type_OId != null) {
        var shop_good_type_Obj = AV.Object.createWithoutData('Shop_good_type', shop_good_type_OId);
    }
    if (shopGoodsTypeParentOId != "" && shopGoodsTypeParentOId != undefined && shopGoodsTypeParentOId != null) {
      var shopGoodsTypeParentObj = AV.Object.createWithoutData('Shop_good_type', shopGoodsTypeParentOId);
    }
    if (shopGoodsTypeParentOId != '' &&  shop_good_type_OId != ''){
      Shop.set('shop_good_type_OId', shop_good_type_OId);
      Shop.set('shop_good_type_Obj', shop_good_type_Obj);
      Shop.set('shopGoodsTypeParentOId', shopGoodsTypeParentOId);
      Shop.set('shopGoodsTypeParentObj', shopGoodsTypeParentObj);
    } else if (shop_good_type_OId == '' && shopGoodsTypeParentOId != '') {
      // Shop.set('shopGoodsTypeParentOId', shopGoodsTypeParentOId);
      // Shop.set('shopGoodsTypeParentObj', shopGoodsTypeParentObj);
      // Shop.unset('shop_good_type_OId')
      // Shop.unset('shop_good_type_Obj');
      Shop.set('shop_good_type_OId', shopGoodsTypeParentOId);
      Shop.set('shop_good_type_Obj', shopGoodsTypeParentObj);
      Shop.unset('shopGoodsTypeParentOId')
      Shop.unset('shopGoodsTypeParentObj');
    } else {
      console.log('商品分类传入值异常，无法写入数据库！')
    }
    // 保存到云端
    return Shop.save().then(function (goods) {
        return goods.id
      }, function (error) {
        console.log(error);
        return error
      }
    )
  }

  function savePic(picArr, goodsOId) {
    let query = new AV.Query("Shop_goodsPic")
    query.equalTo('goodsOId', goodsOId)

    return new Promise(rs => {
      query.find().then(res => {
        rs(res)
      })
    }).then(res => {
      return new Promise(rs => {
        AV.Object.destroyAll(res).then(cc => {
          rs(false)
        }).catch(err => {
          rs(err)
        })

      })

    }).then(res=>{
      if (!res){
        var GoodsPic = AV.Object.extend('Shop_goodsPic');
        var goodsArr = [];
        for (let i = 0; i < picArr.length; i++) {
          var goodsPic = new GoodsPic();
          goodsPic.set("picName", picArr[i])
          goodsPic.set("goodsOId", goodsOId)
          goodsPic.set("sortNum", i + 1)
          goodsArr.push(goodsPic);
        }
        return AV.Object.saveAll(goodsArr).then((pic) => {
          return goodsArr;
        })
      }
    })
    // var GoodsPic = AV.Object.extend('Shop_goodsPic');
    // var goodsArr = [];
    // for (let i = 0; i < picArr.length; i++) {
    //   var goodsPic = new GoodsPic();
    //   goodsPic.set("picName", picArr[i])
    //   goodsPic.set("goodsOId", goodsOId)
    //   goodsPic.set("sortNum", i + 1)
    //   goodsArr.push(goodsPic);
    // }
    // return AV.Object.saveAll(goodsArr).then((pic) => {
    //   return goodsArr;
    // })

  }

  function saveModel(models, goodsOId) {
    let query = new AV.Query("Shop_goods_model_stock")
    query.equalTo('goodsOId', goodsOId)

    return new Promise(rs => {
      query.find().then(res => {
        rs(res)
      })
    }).then(res => {
      return new Promise(rs => {
        AV.Object.destroyAll(res).then(cc => {
          rs(false)
        }).catch(err => {
          rs(err)
        })

      })

    }).then(res=>{
      if (!res){
        var GoodsModel = AV.Object.extend('Shop_goods_model_stock');
        var modelArr = [];
        for (let i = 0; i < models.length; i++) {
          var goodsModel = new GoodsModel();
          var goodsObj = AV.Object.createWithoutData("Shop_goods", goodsOId)
          goodsModel.set("stock", Number(models[i].stock));
          goodsModel.set("model", models[i].model);
          goodsModel.set("goodsOId", goodsOId);
          goodsModel.set("goodsObj", goodsObj);
          goodsModel.set("sortNum", i + 1)
          modelArr.push(goodsModel);
        }
        return AV.Object.saveAll(modelArr).then((pic) => {
          return modelArr;
        }, (reject) => {
          console.log("-----------------------------" + reject)
          return false
        })
      }
    })
  }
})

//店铺商品删除
router.post('/shopGoodsDel', function (req, res) {
  let goodsOId = req.body.objectId
  if (goodsOId != "" && goodsOId != undefined && goodsOId != null) {
    var goodsObj = AV.Object.createWithoutData("Shop_goods", goodsOId)
    goodsObj.set('status', -1);
    goodsObj.save().then(goods=>{
      res.json(common.getReturnArr("OK", "10000", "商品删除成功！", goods.id));
    }).catch(error=>{
      console.log('shopGoodsDelError',error)
      res.json(common.getErrArr(error.msg));
    })
  } else  {
    res.json(common.getErrArr('请传入商品ID！'));
  }
})
//获取订单退款记录
router.post('/getOrderRefund', async function (req, res) {
  var shopInfo = await getShopInfo(req.currentUser.id)
  let shopOId = shopInfo.shopOId
  // console.log(req.body)
  let page = req.body.page;
  let num = req.body.num;
  let orderOId = req.body.orderOId
  let orderBuyerName = req.body.orderBuyerName
  let orderReceiver = req.body.orderReceiver
  let orderStatus = Number(req.body.orderStatus)
  if (page == '' || page == undefined || page == null) {
    page = 1;
  } else {
    page = parseInt(page);
  }
  if (num == '' || num == undefined || num == null) {
    num = 10
  } else {
    num = parseInt(num)
  }
  let query = new AV.Query('Shop_order');
  query.equalTo('shopOId', shopOId)
  if (orderStatus != "" && orderStatus != undefined && orderStatus != null) {
    query.equalTo('status', orderStatus)
  } else {
    query.lessThan('status', 0);

  }
  if (orderOId != "" && orderOId != undefined && orderOId != null) {
    query.equalTo("objectId", orderOId);
  }
  if (orderBuyerName != "" && orderBuyerName != undefined && orderBuyerName != null) {
    let user = new AV.Query('_User');
    user.contains('nickName',orderBuyerName)
    query.matchesQuery('buyerObj',user)
  }
  if (orderReceiver != "" && orderReceiver != undefined && orderReceiver != null) {
    query.contains('receiver',orderReceiver)
  }

  query.skip((page - 1) * num);
  query.limit(num);
  query.include('buyerObj');
  query.include('orderRefundObj');
  query.descending('createdAt');
  query.find().then(result=>{
    query.count().then(count=>{
      let obj = {}
      let data = []
      result.map(item=>{
        let tempObj = {}
        tempObj['objectId'] = item.id //订单ID
        tempObj['orderCode'] = item.get('orderCode')
        // tempObj['orderOId'] = item.get('orderObj') ? item.get('orderObj').get('objectId') : ''; //退款订单ID
        tempObj["buyerName"] = item.get("buyerObj") ? item.get("buyerObj").get("nickName") : '';
        tempObj['receiver'] = item.get('receiver'); //收货人
        tempObj['totalPrice'] = item.get('totalPrice')//总价
        tempObj['status'] = item.get('status')//订单状态
        tempObj["createdAt"] = moment(item.get('payTime')).format('YYYY年MM月DD日 HH:mm:ss'); //退款记录创建时间
        tempObj['title'] = item.get('orderRefundObj') ? item.get('orderRefundObj').get('title') : '';//退款状态
        tempObj['refundFee'] = item.get('orderRefundObj') ? item.get('orderRefundObj').get('refundFee') : '';//申请退款金额
        tempObj['refundReason'] = item.get('orderRefundObj') ? item.get('orderRefundObj').get('refundReason') : '';//退款原因
        tempObj['sellerFee'] = item.get('sellerFee') //卖家所得费用
        data.push(tempObj)
      })
      obj.data = data;
      obj.total = count;
      res.json(common.getReturnArr("OK", "10000", "退款订单获取成功！", obj));
    }).catch(countError=>{

    })
  }).catch(error=>{
    console.log('getOrderRefund',error)
    res.json(common.getErrArr(error.msg));
  })

})

//获取订单退款详情
router.post('/getOrderRefundDetail', function (req, res) {
  let objectId = req.body.objectId
  if (objectId == "" && objectId == undefined && objectId == null) {
    console.log('getOrderDetail,请传入objectId!')
    res.json(common.getErrArr('请传入objectId！'));
  } else {
    let query = new AV.Query('Shop_order')
    // query.include('sellerObj') //卖家
    query.include('buyerObj') //买家
    query.include('orderRefundObj')
    query.get(objectId).then(async orderObj=>{
      let tempObj = {}
      tempObj['objectId'] = orderObj.id
      let goodsInfoArr = await getGoodsInfos(orderObj.get('orderGoodsArray'))
      tempObj['orderGoodsArray'] = goodsInfoArr // 商品信息
      // tempObj["buyerUserAvatar"] = orderObj.get('buyerObj') ? orderObj.get('buyerObj').get('userAvatar').url() : "";
      if (orderObj.get('buyerObj').get('userAvatar')){
        tempObj["buyerUserAvatar"] = orderObj.get('buyerObj').get('userAvatar').url()
      } else {
        tempObj["buyerUserAvatar"] = "";
      }
      tempObj['buyerNickName'] = orderObj.get('buyerObj') ? orderObj.get('buyerObj').get('nickName') : '' //下单人昵称
      tempObj['buyermobilePhoneNumber'] = orderObj.get('buyerObj') ? orderObj.get('buyerObj').get('mobilePhoneNumber') : ''; //下单人电话
      tempObj['receiver'] = orderObj.get('receiver') //收货人名称
      tempObj['phone'] = orderObj.get('phone') // 收货人电话
      tempObj['address'] = orderObj.get('address') // 收货地址
      tempObj['orderCode'] = orderObj.get('orderCode') //订单号
      tempObj["createdAt"] = moment(orderObj.createdAt).format('YYYY年MM月DD日 HH:mm:ss'); //下单时间
      // tempObj['payType'] = orderObj.get('payType') //1支付宝2微信
      if (orderObj.get('payType') == '1'){
        tempObj['payType'] = '支付宝'
      } else {
        tempObj['payType'] = '微信'
      }
      tempObj["payTime"] = moment(orderObj.get('payTime')).format('YYYY年MM月DD日 HH:mm:ss'); //支付时间
      tempObj['totalPrice'] = orderObj.get('totalPrice') //总价(含邮费)
      tempObj['sellerFee'] = orderObj.get('sellerFee') //卖家所得费用
      tempObj['remark'] = orderObj.get('remark') //买家备注
      tempObj['orderRemark'] = orderObj.get('orderRemark') //订单备注
      tempObj['parentOrderCode'] = orderObj.get('parentOrderCode') //父订单号
      tempObj['fare'] = orderObj.get('fare') //运费
      tempObj['refundReason'] = orderObj.get('orderRefundObj') ?  orderObj.get('orderRefundObj').get('refundReason') : '';
      let score= orderObj.get('score') //积分
      if (score){
        tempObj['score'] = score
      } else {
        tempObj['score'] = 0
      }
      let orderStatus = orderObj.get('status') //订单状态
      if (orderStatus == -1){
        tempObj['status'] = '已同意'
      } else if (orderStatus == -2){
        tempObj['status'] = '已退款'
      } else if (orderStatus == -3){
        tempObj['status'] = '待处理'
      } else {
        tempObj['status'] = '非退款订单状态'
      }
      res.json(common.getReturnArr("OK", "10000", "订单详情获取成功！", tempObj));
    }).catch(error=>{
      console.log('getOrderRefundDetail',error)
      res.json(common.getErrArr(error.msg));
    })
  }

})

//获取商品信息
async function getGoodsInfos(goodsArr){
  let goodsOIdArr = []
  for (let i=0; i<goodsArr.length;i++){
    goodsOIdArr.push(goodsArr[i].get('objectId'))
  }
  var query = new AV.Query('Shop_order_goods');
  query.containedIn('objectId',goodsOIdArr)
  query.include('scoreShopGoodsObj')
  return query.find().then(goodsObjs=>{
    let goodsInfoArr = []
    for (let i=0; i<goodsObjs.length;i++){
      let score = goodsObjs[i].get('scoreShopGoodsObj') ? goodsObjs[i].get('scoreShopGoodsObj').get('score') : '0'
      let tempObj = {
        'objectId':goodsObjs[i].get('objectId'),
        'goodsName':goodsObjs[i].get('goodsName'), //商品名称
        'price':goodsObjs[i].get('price'), //商品价格
        'goodsPicURL':goodsObjs[i].get('goodsPicURL'), //商品图片
        'num':goodsObjs[i].get('num'), //购买数量
        'goodsModel':goodsObjs[i].get('goodsModel'), //商品型号
        'allFee':goodsObjs[i].get('allFee'), //订单商品费用
        'sellerFee':goodsObjs[i].get('sellerFee'), //卖家所得费用
        'score':score//积分
      }
      goodsInfoArr.push(tempObj)

    }
    return goodsInfoArr
  }).catch(error=>{
    console.log('getGoodsInfoError',error)
  })
}

//操作订单退款
router.post('/handleOrderRefund', function (req, res) {
  // console.log(req.body)
  let orderOId = req.body.orderOId
  let status = Number(req.body.status)
  let refundFee = Number(req.body.refundFee)
  let currentUserOId = req.currentUser.id
  let content = req.body.refundAnswer
  let refundReason = req.body.refundReason
  // orderObj.set("refundReason", orderObj.get("orderRefundObj").get('refundReason'));

  let title =''
  let sendContent =''
  let query = new AV.Query('Shop_order');
  query.get(orderOId).then(async orderObj=>{
    orderObj.set("oldStatus", orderObj.get("status"));
    if (status == 0) {
      title = "拒绝退款";
      orderObj.set("status", orderObj.get("refundStatus"));
      orderObj.set("task", orderObj.get("refundTask"));
      orderObj.set("taskTime", orderObj.get("refundTaskTime"));
      sendContent = "卖家拒绝了订单" + orderObj.get("orderCode") + "的退款申请，理由是：" + content;
    } else if (status == 1) {
      title = "同意退款";
      orderObj.set("status", apis["order"]["status_refunding"]);
      orderObj.set("task", null);
      orderObj.set("taskTime", null);
      sendContent = "卖家同意了订单" + orderObj.get("orderCode") + "的退款申请，退款金额为："+refundFee+"元，系统审核后，款项将退回到您的原支付途径。";
    }
    //保存退款明细
    let orderRefundMap = {};
    orderRefundMap["title"] = title;
    orderRefundMap["content"] = content;
    orderRefundMap["uId"] = currentUserOId;
    orderRefundMap["orderOId"] = orderOId;
    orderRefundMap["pics"] = [];
    orderRefundMap["type"] = "2";
    orderRefundMap["refundReason"] = refundReason;
    orderRefundMap["refundAnswer"] = content;
    if (orderObj.get("orderRefundObj") != null && orderObj.get("orderRefundObj") != "")
      // orderRefundMap["refundFee"] = common.formatMoney(orderObj.get("orderRefundObj").get("refundFee"));
      orderRefundMap["refundFee"] = common.formatMoney(refundFee);
    await addOrderRefundDetail(orderRefundMap, function (err, orderRefundObj) {
      // console.log(orderRefundObj)
      if (err != null) {
        // return callback(err, null);
        console.log('addOrderRefundDetailErr',err)
        res.json(common.getErrArr(err));
      } else {
        orderObj.set("orderRefundObj", orderRefundObj);

        var toUserOId = orderObj.get("buyerOId");
        // 推送交易消息
        var msg_content = {};
        msg_content["content"] = sendContent;

        var msg_extra = {};
        msg_extra["extra"] = apis['message_profession_code']['transaction_code']; //交易消息代码
        msg_extra["code"] = apis['message_type_code']['word']; //文本消息
        msg_extra["content"] = msg_content;

        var base64Content = new Buffer(JSON.stringify(msg_extra)).toString('base64');
        base64Content = base64Content.replace(/\+/g, "@");
        base64Content = base64Content.replace(/\=/g, "");

        var sendObj = {};
        sendObj["operation"] = "";
        sendObj["sourceUserId"] = "";
        sendObj["targetUserId"] = "";
        sendObj["extra"] = base64Content;
        message.publish("admin", toUserOId, "RC:ContactNtf", JSON.stringify(sendObj), "json", function (err, result1) {
        });

        //记录到系统消息中
        var SystemMessage = common.getEntity('SystemMessage');
        var systemMessage = new SystemMessage();
        systemMessage.set('targetUserOId', toUserOId);
        systemMessage.set('targetUserObj', {"__type": "Pointer", className: "_User", objectId: toUserOId});
        systemMessage.set('sortTime', common.getCurrTime());
        systemMessage.set('status', 0);
        systemMessage.set('messageType', 2);
        systemMessage.set('isBuyer', 1);
        systemMessage.set('orderObj', {"__type": "Pointer", className: "Shop_order", objectId: orderOId});
        systemMessage.set('title', title);
        systemMessage.set('content', msg_content['content']);
        systemMessage.save();
        orderObj.save().then(newOrderObj=>{
          res.json(common.getReturnArr("OK", "10000", "退款操作成功！", "success"));
        }).catch(newOrderObjErr=>{
          res.json(common.getReturnArr("OK", "10000", "退款操作失败！", newOrderObjErr.message));
        })
      }
    })
  }).catch(error=>{
    console.log('handleOrderRefund',error)
    res.json(common.getErrArr(error.msg));

  })
})
//添加订单退款明细
function addOrderRefundDetail(orderRefundMap,cb) {
  if (orderRefundMap == null || orderRefundMap == "" || orderRefundMap == undefined)
    return cb("无效的对象", null);
  var Shop_order_refund = common.getEntity("Shop_order_refund");
  var orderRefundObj = new Shop_order_refund();
  orderRefundObj.set("title", orderRefundMap["title"]);
  if (orderRefundMap["contentCode"] != null && orderRefundMap["contentCode"] != undefined) {
    orderRefundObj.set("refundReasonCode", orderRefundMap["contentCode"]);
  }
  orderRefundObj.set("refundReason", orderRefundMap["content"]);
  if (orderRefundMap["refundFee"] != null && orderRefundMap["refundFee"] != "" && orderRefundMap["refundFee"] != undefined)
    orderRefundObj.set("refundFee", orderRefundMap["refundFee"]);
  if (orderRefundMap["uId"] != "") {
    orderRefundObj.set("refunder", orderRefundMap["uId"]);
    orderRefundObj.set("refundObj", {"__type": "Pointer", className: "_User", objectId: orderRefundMap["uId"]});
  }
  if (orderRefundMap["refundAnswer"] != ""){
    orderRefundObj.set("refundAnswer", orderRefundMap["refundAnswer"]);
  }
  orderRefundObj.set("refundReason", orderRefundMap["refundReason"]);
  orderRefundObj.set("orderOId", orderRefundMap["orderOId"]);
  orderRefundObj.set("orderObj", {"__type": "Pointer", className: "Shop_order", objectId: orderRefundMap["orderOId"]});
  orderRefundObj.set("type", orderRefundMap["type"]);
  orderRefundObj.set("picArray",orderRefundMap["pics"]);
  orderRefundObj.save().then(newOrderRefundObj => {
    return cb(null, newOrderRefundObj);
  }).catch(orderRefundObjSaveError => {
    console.log('orderRefundObjSaveError', orderRefundObjSaveError)
  })
}
  //保存上传凭证
  // saveOrderRefundPics(orderRefundMap["pics"],function(err,picList){
  //   if(err){
  //     return cb(err,null);
  //   }else{
  //     orderRefundObj.set("picArray",picList);
  //     orderRefundObj.save(null, {
  //       success : function(newOrderRefundObj) {
  //         return cb(null,newOrderRefundObj);
  //       },error:function(errObj,err){
  //         return cb(err.message,null);
  //       }
  //     });
  //   }
  // });
// }
//保存订单退款凭证
// function saveOrderRefundPics(pics,cb){
//   if(pics.length==0)
//     return cb(null,pics);
//   var shopCommonPicsArry=[];
//   var picIds=[];
//   for ( var i = 0; i < pics.length; i++) {
//     picIds.push(pics[i]["objectId"]);
//   }
//   //先查询旧的凭证
//   var query = new AV.Query('Shop_common_pic');
//   query.containedIn("picName", picIds);
//   query.find({
//     success : function(picObjs) {
//       var picMap={};
//       for ( var i = 0; i < picObjs.length; i++) {
//         picObjs[i].set("sortNum",i+1);
//         picMap[picObjs[i].get("picName")]=picObjs[i];
//       }
//       var ShopCommonPic = common.getEntity("Shop_common_pic");
//       for ( var i = 0; i < picIds.length; i++) {
//         if(picMap[picIds[i]]==null){
//           var shopcommonPic = new ShopCommonPic();
//           shopcommonPic.set("picName", picIds[i]);
//           shopcommonPic.set("sortNum",i+1);
//           shopCommonPicsArry.push(shopcommonPic);
//         }
//       }
//       AV.Object.saveAll(shopCommonPicsArry, function(list, error) {
//         for ( var i = 0; i < picObjs.length; i++) {
//           list.push(picObjs[i]);
//         }
//         list.sort(function(a,b){return b.get("sortNum")-a.get("sortNum")});
//         return cb(null,list);
//       });
//     },error:function(err){
//       return cb(err,null);
//     }
//   })
// }
//获取卖家发起退款列表
router.post('/getOrderSellerRefund', async function (req, res) {
  var shopInfo = await getShopInfo(req.currentUser.id)
  let shopOId = shopInfo.shopOId
  // console.log(req.body)
  let page = req.body.page;
  let num = req.body.num;
  let orderOId = req.body.orderOId
  let orderBuyerName = req.body.orderBuyerName
  let orderReceiver = req.body.orderReceiver
  let orderCode = req.body.orderCode
  if (page == '' || page == undefined || page == null) {
    page = 1;
  } else {
    page = parseInt(page);
  }
  if (num == '' || num == undefined || num == null) {
    num = 10
  } else {
    num = parseInt(num)
  }
  let query = new AV.Query('Shop_order');
  query.equalTo('shopOId', shopOId)
  query.equalTo('status', 2);
  if (orderOId != "" && orderOId != undefined && orderOId != null) {
    query.equalTo("objectId", orderOId);
  }
  if (orderCode != "" && orderCode != undefined && orderCode != null) {
    query.equalTo("orderCode", orderCode);
  }
  if (orderBuyerName != "" && orderBuyerName != undefined && orderBuyerName != null) {
    let user = new AV.Query('_User');
    user.contains('nickName',orderBuyerName)
    query.matchesQuery('buyerObj',user)
  }
  if (orderReceiver != "" && orderReceiver != undefined && orderReceiver != null) {
    query.contains('receiver',orderReceiver)
  }

  query.skip((page - 1) * num);
  query.limit(num);
  query.include('buyerObj');
  query.include('orderRefundObj');
  query.descending('createdAt');
  query.find().then(result=>{
    query.count().then(count=>{
      let obj = {}
      let data = []
      result.map(item=>{
        let tempObj = {}
        tempObj['objectId'] = item.id //订单ID
        tempObj['orderCode'] = item.get('orderCode')
        // tempObj['orderOId'] = item.get('orderObj') ? item.get('orderObj').get('objectId') : ''; //退款订单ID
        tempObj["buyerName"] = item.get("buyerObj") ? item.get("buyerObj").get("nickName") : '';
        tempObj['receiver'] = item.get('receiver'); //收货人
        tempObj['totalPrice'] = common.formatMoney(item.get('totalPrice'))//总价
        tempObj['status'] = item.get('status')//订单状态
        tempObj["createdAt"] = moment(item.get('payTime')).format('YYYY年MM月DD日 HH:mm:ss'); //退款记录创建时间
        tempObj['title'] = item.get('orderRefundObj') ? item.get('orderRefundObj').get('title') : '';//退款状态
        tempObj['refundFee'] = item.get('orderRefundObj') ? item.get('orderRefundObj').get('refundFee') : '';//申请退款金额
        tempObj['refundReason'] = item.get('orderRefundObj') ? item.get('orderRefundObj').get('refundReason') : '';//退款原因
        tempObj['sellerFee'] = item.get('sellerFee') //卖家所得费用
        data.push(tempObj)
      })
      obj.data = data;
      obj.total = count;
      res.json(common.getReturnArr("OK", "10000", "待发货订单获取成功！", obj));
    }).catch(countError=>{

    })
  }).catch(error=>{
    console.log('getOrderRefund',error)
    res.json(common.getErrArr(error.msg));
  })

})

//卖家发起退款操作
router.post('/handleOrderSellerRefund', async function (req, res) {
  // console.log(req.body)
  let orderOId = req.body.orderOId
  let refundFee = Number(req.body.refundFee)
  let refundReason = req.body.refundReason
  let status = 1
  let currentUserOId = req.currentUser.id
  let content = req.body.refundReason
  let title =''
  let sendContent =''
  let query = new AV.Query('Shop_order');
  query.get(orderOId).then(async orderObj=>{
    orderObj.set("oldStatus", orderObj.get("status"));
    title = "同意退款";
    orderObj.set("status", apis["order"]["status_refunding"]);
    orderObj.set("task", null);
    orderObj.set("taskTime", null);
    sendContent = "卖家发起了订单" + orderObj.get("orderCode") + "的退款申请，退款金额为："+refundFee+"元，系统审核后，款项将退回到您的原支付途径。";
    //保存退款明细
    let orderRefundMap = {};
    orderRefundMap["title"] = title;
    orderRefundMap["content"] = content;
    orderRefundMap["uId"] = currentUserOId;
    orderRefundMap["orderOId"] = orderOId;
    orderRefundMap["pics"] = [];
    orderRefundMap["type"] = "2";
    orderRefundMap["refundReason"] = refundReason;
    // if (orderObj.get("orderRefundObj") != null && orderObj.get("orderRefundObj") != "")
    //   orderRefundMap["refundFee"] = common.formatMoney(refundFee);
    orderRefundMap["refundFee"] = common.formatMoney(refundFee);
    await addOrderRefundDetail(orderRefundMap, function (err, orderRefundObj) {
      // console.log(orderRefundObj)
      if (err != null) {
        // return callback(err, null);
        console.log('addOrderRefundDetailErr',err)
        res.json(common.getErrArr(err));
      } else {
        orderObj.set("orderRefundObj", orderRefundObj);

        var toUserOId = orderObj.get("buyerOId");
        // 推送交易消息
        var msg_content = {};
        msg_content["content"] = sendContent;

        var msg_extra = {};
        msg_extra["extra"] = apis['message_profession_code']['transaction_code']; //交易消息代码
        msg_extra["code"] = apis['message_type_code']['word']; //文本消息
        msg_extra["content"] = msg_content;

        var base64Content = new Buffer(JSON.stringify(msg_extra)).toString('base64');
        base64Content = base64Content.replace(/\+/g, "@");
        base64Content = base64Content.replace(/\=/g, "");

        var sendObj = {};
        sendObj["operation"] = "";
        sendObj["sourceUserId"] = "";
        sendObj["targetUserId"] = "";
        sendObj["extra"] = base64Content;
        message.publish("admin", toUserOId, "RC:ContactNtf", JSON.stringify(sendObj), "json", function (err, result1) {
        });

        //记录到系统消息中
        var SystemMessage = common.getEntity('SystemMessage');
        var systemMessage = new SystemMessage();
        systemMessage.set('targetUserOId', toUserOId);
        systemMessage.set('targetUserObj', {"__type": "Pointer", className: "_User", objectId: toUserOId});
        systemMessage.set('sortTime', common.getCurrTime());
        systemMessage.set('status', 0);
        systemMessage.set('messageType', 2);
        systemMessage.set('isBuyer', 1);
        systemMessage.set('orderObj', {"__type": "Pointer", className: "Shop_order", objectId: orderOId});
        systemMessage.set('title', title);
        systemMessage.set('content', msg_content['content']);
        systemMessage.save();
        orderObj.save().then(newOrderObj=>{
          res.json(common.getReturnArr("OK", "10000", "卖家退款操作成功！", "success"));
        }).catch(newOrderObjErr=>{
          res.json(common.getReturnArr("OK", "10000", "卖家退款操作失败！", newOrderObjErr.message));
        })
      }
    })
  }).catch(error=>{
    console.log('handleOrderSellerRefund',error)
    res.json(common.getErrArr(error.msg));

  })
})

//获取提现列表
router.post('/getWithdrawDepositList', function (req, res) {
  let page = req.body.page;
  let num = req.body.num;
  let objectId = req.body.objectId
  let bankName = req.body.bankName
  let bankNo = req.body.bankNo
  let withdrawStatus = req.body.withdrawStatus
  if (page == '' || page == undefined || page == null) {
    page = 1;
  } else {
    page = parseInt(page);
  }
  if (num == '' || num == undefined || num == null) {
    num = 10
  } else {
    num = parseInt(num)
  }
  let query = new AV.Query('Shop_account_detail');
  query.equalTo('userOId', req.currentUser.id)
  query.exists('withdrawStatus')
  // query.equalTo('status', 2);
  if (objectId != "" && objectId != undefined && objectId != null) {
    query.equalTo("objectId", objectId);
  }
  if (bankName != "" && bankName != undefined && bankName != null) {
    query.contains("bankName", bankName);
  }
  if (bankNo != "" && bankNo != undefined && bankNo != null) {
    query.equalTo('bankNo',bankNo)
  }
  if (withdrawStatus != "" && withdrawStatus != undefined && withdrawStatus != null) {
    query.equalTo('withdrawStatus',withdrawStatus)
  }

  query.skip((page - 1) * num);
  query.limit(num);
  query.descending('createdAt');
  query.find().then(result=>{
    query.count().then(count=>{
      let obj = {}
      let data = []
      result.map(item=>{
        let tempObj = {}
        tempObj.objectId = item.id //订单ID
        tempObj.name = item.get('name') //提现人
        tempObj.bankName = item.get('bankName')
        tempObj.bankNo = item.get('bankNo')
        tempObj.remark = item.get('remark')
        tempObj.procedureFee = item.get('procedureFee') //提现手续费
        tempObj.changeMoney = item.get('changeMoney') //变动金额
        tempObj.withdrawStatus = item.get('withdrawStatus')//提现状态
        tempObj.procedureRate = item.get('procedureRate')//提现时利率
        tempObj.createdAt = moment(item.get('createdAt')).format('YYYY年MM月DD日 HH:mm:ss'); //提现记录创建时间
        data.push(tempObj)
      })
      obj.data = data;
      obj.total = count;
      res.json(common.getReturnArr("OK", "10000", "提现记录列表获取成功！", obj));
    }).catch(countError=>{

    })
  }).catch(error=>{
    console.log('getWithdrawDepositList',error)
    res.json(common.getErrArr(error.msg));
  })
})

//获取银行卡列表
router.post('/getBankList', function (req, res) {
  let page = req.body.page;
  let num = req.body.num;
  let objectId = req.body.objectId
  let userOId = req.currentUser.id
  let bankName = req.body.bankName
  let bankNo = req.body.bankNo
  let name = req.body.name
  if (page == '' || page == undefined || page == null) {
    page = 1;
  } else {
    page = parseInt(page);
  }
  if (num == '' || num == undefined || num == null) {
    num = 10
  } else {
    num = parseInt(num)
  }
  let query = new AV.Query('Shop_account_bank');
  query.equalTo('userOId', userOId);
  if (objectId != "" && objectId != undefined && objectId != null) {
    query.equalTo("objectId", objectId);
  }
  if (bankName != "" && bankName != undefined && bankName != null) {
    query.contains("bankName", bankName);
  }
  if (bankNo != "" && bankNo != undefined && bankNo != null) {
    query.equalTo('bankNo',bankNo)
  }
  if (name != "" && name != undefined && name != null) {
    query.contains('name',name)
  }

  query.skip((page - 1) * num);
  query.limit(num);
  query.descending('isDefault');
  query.find().then(result=>{
    query.count().then(count=>{
      let obj = {}
      let data = []
      result.map(item=>{
        let tempObj = {}
        tempObj.objectId = item.id
        tempObj.name = item.get('name')
        tempObj.bankName = item.get('bankName')
        tempObj.branch = item.get('branch')
        tempObj.bankNo = item.get('bankNo')
        tempObj.name = item.get('name')
        tempObj.isDefault = item.get('isDefault') //是否默认 0不是 1是
        tempObj.updatedAt = moment(item.get('updatedAt')).format('YYYY年MM月DD日 HH:mm:ss');
        tempObj.createdAt = moment(item.get('createdAt')).format('YYYY年MM月DD日 HH:mm:ss');
        data.push(tempObj)
      })
      obj.data = data;
      obj.total = count;
      res.json(common.getReturnArr("OK", "10000", "绑定银行卡列表获取成功！", obj));
    }).catch(countError=>{
      console.log('getBankListCount',countError)
      res.json(common.getErrArr(error.msg));
    })
  }).catch(error=>{
    console.log('getBankList',error)
    res.json(common.getErrArr(error.msg));
  })
})

//获取银行名称列表
router.post('/getBankCardListFromDictionary', function (req, res) {
  let query = new AV.Query('Dictionary')
  query.equalTo("type", '9');
  query.descending('code')
  query.find().then(bankObjs=>{
    let data = []
    bankObjs.map(item=>{
      let tempObj = {
        label:item.get('name'),
        value:item.get('code')
      }
      data.push(tempObj)
    })
    res.json(common.getReturnArr("OK", "10000", "银行卡列表获取成功！", data));
  }).catch(error=>{
    console.log('getBankCardListFromDictionary',error)
    res.json(common.getErrArr(error.msg));
  })
})

//获取银行卡数量
async function bankCardsCount(userOId){
  let query = new AV.Query('Shop_account_bank');
  query.equalTo('userOId',userOId)
  return query.count().then(count=>{
    return count
  }).catch(error=>{
    return -1
    console.log('bankCardsCount',error)
  })
}
//添加及编辑银行卡信息
router.post('/updateBankCard', async function (req, res) {
  // console.log(req.body)
  let objectId = req.body.objectId
  let userOId = req.currentUser.id
  let name = req.body.name
  let bankName = req.body.bankName
  let branch = req.body.branch
  let bankNo = req.body.bankNo
  var isDefault = ''
  var count = await bankCardsCount(userOId)
  if (count < 1){
    isDefault = '1'
  } else {
    isDefault = req.body.isDefault
  }
  if (objectId != "" && objectId != undefined && objectId != null) {
    var shopAccountBank = AV.Object.createWithoutData('Shop_account_bank', objectId);
  } else {
    let Shop_account_bank = AV.Object.extend("Shop_account_bank");
    var shopAccountBank = new Shop_account_bank();
  }
  shopAccountBank.set("name", name);
  shopAccountBank.set("bankName", bankName);
  shopAccountBank.set("branch", branch);
  shopAccountBank.set("bankNo", bankNo);
  shopAccountBank.set("userOId",userOId);
  shopAccountBank.set("isDefault",isDefault);
  shopAccountBank.save().then(async shopAccountBankObj=>{
    let bankCardCount = await bankCardsCount(userOId)
    if (bankCardCount > 1 && isDefault == '1'){
      await setDefaultBankCardFunction(shopAccountBankObj.id,userOId,result=>{
        if (!result) {
          console.log('setDefaultBankCardFunction','默认设置失败')
          res.json(common.getErrArr('默认设置失败'));
          return
        }
      })
    }
    if (objectId != "" && objectId != undefined && objectId != null){
      if (req.body.isDefault == '0' && bankCardCount > 1) {
        let otherBankCardsIdArr = await getOtherBankCardsIDArray(objectId,userOId)
        console.log('otherBankCardsIdArr',otherBankCardsIdArr)
        await setDefaultBankCardFunction(otherBankCardsIdArr[0],userOId,setDefaultResult=>{
          if (!setDefaultResult){
            res.json(common.getErrArr('默认银行卡改非默认失败！'));
            return
          }
        })
      }
    }
    res.json(common.getReturnArr("OK", "10000", "更新银行卡成功！", shopAccountBankObj.id));
  }).catch(error=>{
    console.log('addBankCard',error)
    res.json(common.getErrArr(error.msg));
  })
})
//设置默认银行卡
router.post('/setDefaultBankCard', async function (req, res) {
  let objectId = req.body.objectId
  let userOId = req.currentUser.id
  await setDefaultBankCardFunction(objectId,userOId,result=>{
    if (result) {
      res.json(common.getReturnArr("OK", "10000", "银行卡设置默认成功！", result));
    } else {
      res.json(common.getErrArr("银行卡设置默认失败！"));
    }
  })
})
//设置默认银行卡方法
async function setDefaultBankCardFunction (objectId,userOId,callBack){
  let query = new AV.Query('Shop_account_bank')
  query.equalTo('userOId',userOId)
  query.find().then(bankInfos=>{
    bankInfos.map(item=>{
      if (item.id == objectId){
        item.set('isDefault','1')
      } else {
        if (item.get('isDefault') == '1'){
          item.set('isDefault','0')
        }
      }
    })
    AV.Object.saveAll(bankInfos).then(bankInfoSaveResult=>{
      callBack(bankInfoSaveResult.length)
    }).catch(err=>{
      console.log('setDefaultBankCardSave',err)
      callBack(err)
    })
  }).catch(error=>{
    console.log('setDefaultBankCard',error)
    callBack(error)
  })
}
//删除银行卡
router.post('/removeBankCard', async function (req, res) {
  let objectId = req.body.objectId
  let isDefault = req.body.isDefault
  let userOId = req.currentUser.id
  var count = await bankCardsCount(userOId)
  let shopAccountBank = AV.Object.createWithoutData('Shop_account_bank', objectId);
  shopAccountBank.destroy().then(async destroyResult=>{
    if (count > 1 && isDefault == '1'){
      let bankCardsOIds = await getBankCardsOIdsArrey(userOId)
      if (bankCardsOIds.length > 0) {
        await setDefaultBankCardFunction(bankCardsOIds[0],userOId,result=>{
          if (result) {
            res.json(common.getReturnArr("OK", "10000", "银行卡删除成功！", destroyResult.id));
          } else {
            res.json(common.getErrArr('设置默认银行卡失败！'));
          }
        })
      } else {
        res.json(common.getErrArr('没有可移除的银行卡！'));
      }
    } else {
      res.json(common.getReturnArr("OK", "10000", "银行卡删除成功！", destroyResult.id));
    }
  }).catch(error=>{
    console.log('setDefaultBankCard',error)
    res.json(common.getErrArr(error.msg));
  })
})
//获取银行卡OID数组
async function getBankCardsOIdsArrey(userOId) {
  let query = new AV.Query('Shop_account_bank');
  query.equalTo('userOId',userOId)
  query.descending('updatedAt')
  return query.find().then(bankCards=>{
    let bankCardsOIds = []
    bankCards.map(item=>{
      bankCardsOIds.push(item.id)
    })
    return bankCardsOIds
  }).catch(error=>{
    console.log('changeDefault',error)
    return
  })
}
//获取除传入银行卡以外的其他银行卡OID数组
async function getOtherBankCardsIDArray(objectId,userOId) {
  let query = new AV.Query('Shop_account_bank');
  query.equalTo('userOId',userOId)
  query.descending('updatedAt')
  return query.find().then(bankCards=>{
    let bankCardsOIds = []
    bankCards.map(item=>{
      bankCardsOIds.push(item.id)
    })
    // console.log(bankCardsOIds)
    let index = bankCardsOIds.indexOf(objectId);
    if (index > -1) {
      bankCardsOIds.splice(index, 1);
    }
    // console.log(bankCardsOIds)
   return bankCardsOIds
  }).catch(error=>{
    console.log('changeDefault',error)
    return
  })
}

//获取银行卡列表用于提现申请
router.post('/getBankListForApplyWithdrawDeposit', function (req, res) {

  let userOId = req.currentUser.id
  let query = new AV.Query('Shop_account_bank');
  query.equalTo('userOId', userOId);
  query.descending('isDefault');
  query.find().then(result=>{
    let data = []
    result.map(item=>{
      let tempObj = {}
      tempObj.key = item.id //订单ID
      tempObj.label = item.get('bankName') +' 尾号：'+ item.get('bankNo').substr(item.get('bankNo').length-4)
      data.push(tempObj)
    })
    res.json(common.getReturnArr("OK", "10000", "银行卡列表获取成功！", data));
  }).catch(error=>{
    console.log('getBankList',error)
    res.json(common.getErrArr(error.msg));
  })
})
exports.findUsableMoney = findUsableMoney;
function findUsableMoney(uId, callback) {
  if (uId == null || uId == "" || uId == undefined) {
    return callback(0);
  } else {
    var query = new AV.Query('Shop_account');
    query.equalTo("userOId", uId);
    query.first({
      success: function (accountObj) {
        var money = 0;
        if (accountObj != null) {
          var withdrawFrozenMoney = accountObj.get("withdrawFrozenMoney");
          if (withdrawFrozenMoney == null || withdrawFrozenMoney == undefined)
            withdrawFrozenMoney = 0.00;
          money = common.formatMoney(accountObj.get("frozenMoney")+accountObj.get("currentMoney") - withdrawFrozenMoney);
        }
        return callback(money);
      }, error: function (error) {
        return callback(0);
      }
    });
  }
}
/**
 * 申请提现
 * @param uId
 * @param money
 * @param accountBankOId
 * @param callback
 */
router.post('/applyWithdrawDeposit', function (req, res) {
  var uId = req.currentUser.id
  var money = Number(req.body.changeMoney)
  var accountBankOId = req.body.bankCardId
  // console.log(req.body)
  money = common.formatMoney(money);
  if (isNaN(money)) {
    console.log('applyWithdraw：错误的提现金额！')
    res.json(common.getErrArr('错误的提现金额！'));
  }
  if (money < 10) {
    console.log('applyWithdraw：提现金额不能少于10元！')
    res.json(common.getErrArr('提现金额不能少于10元！'));
  } else {
    //检查是否通过身份认证
    checkAccountIsVerify(uId, function (state, msg) {
      if (state != 1) {
        res.json(common.getErrArr(msg));
      } else {
        //获取用户银行卡信息
        getUserBankObj(uId, accountBankOId, function (bankObj) {
          if (bankObj == null) {
            var resultObj = {};
            resultObj["status"] = "0";
            resultObj["msg"] = "1";
            res.json(common.getErrArr('未检测到已绑定的银行卡！'));
          } else {
            //检查提现金额
            getShopAccount(uId, function (shopAccountObj) {
              if (shopAccountObj == null) {
                res.json(common.getErrArr('无效的账户信息，请稍后再试！'));
              } else {
                if ( shopAccountObj.get("currentMoney") - shopAccountObj.get("withdrawFrozenMoney") < money) {
                  var resultObj = {};
                  resultObj["status"] = "0";
                  resultObj["msg"] = "2";
                  res.json(common.getErrArr("余额不足,可提现："+ (shopAccountObj.get("currentMoney") - shopAccountObj.get("withdrawFrozenMoney"))));
                } else {
                  //提现业务
                  doWithdraw(shopAccountObj, money, bankObj, function (state, msg) {
                    var doWithdrawResultObj = {};
                    doWithdrawResultObj["status"] = state.toString();
                    doWithdrawResultObj["msg"] = msg;
                    res.json(common.getReturnArr("OK", "10000", "申请提现成功，请等待人工审核！！", doWithdrawResultObj));
                  });
                }
              }
            })
          }
        })
      }
    })
  }
})

//获取用户账户信息
function getShopAccount(uId, callback) {
  if (uId == "" || uId == null || uId == undefined) {
    return callback(null);
  } else {
    var query = new AV.Query('Shop_account');
    query.equalTo("userOId", uId);
    query.first().then(verifyObj=>{
      //如果没查询到账户信息，则初始化一个账户信息
      if (verifyObj == null) {
        var ShopAccount = common.getEntity("Shop_account");
        var shopAccount = new ShopAccount();
        shopAccount.set("userOId", uId);
        shopAccount.set("userObj", {"__type": "Pointer", className: "_User", objectId: uId});
        shopAccount.set("currentMoney", 0.00);
        shopAccount.set("frozenMoney", 0.00);
        shopAccount.set("withdrawMoney", 0.00);
        shopAccount.set("withdrawFrozenMoney", 0.00);
        shopAccount.save().then(shopAccountObj=>{
          return callback(shopAccountObj);
        }).catch(err=>{
          console.log('getShopAccount',err)
          return callback(null);
        })
      } else {
        return callback(verifyObj);
      }
    }).catch(error=>{
      console.log(error)
      return callback(null);
    })
  }
}
//检查用户账户是否通过验证
function checkAccountIsVerify(uId, callback) {
  var state = 0;
  var msg = "";
  if (uId == "" || uId == null || uId == undefined) {
    msg = "错误的参数";
    return callback(state, msg);
  } else {
    //检查用户是否通过用户审核
    var query = new AV.Query('Shop_account_verify');
    query.equalTo("userOId", uId);
    query.first().then(verifyObj=>{
      if (verifyObj != null) {
        if (verifyObj.get("status") == "0") {
          msg = "您的账号还在审核中，请等待审核";
        } else if (verifyObj.get("status") == "2") {
          msg = "您的账号审核失败，请重新提交审核资料";
        } else if (verifyObj.get("status") == "1") {
          state = 1;
        } else {
          msg = "您的账号还在审核中，请等待审核";
        }
      } else {
        msg = "请先绑定一个银行账号";
      }
      return callback(state, msg);
    }).catch(error=>{
      msg = error.message;
      return callback(state, msg);
    })
  }
}

/**
 * 获取用户银行卡信息
 * @param accountBankOId
 * @param callback
 */
function getUserBankObj(uId, accountBankOId, callback) {
  if (accountBankOId == "" || accountBankOId == null || accountBankOId == undefined || uId == "" || uId == null || uId == undefined) {
    return callback(null);
  } else {
    var query = new AV.Query('Shop_account_bank');
    query.equalTo("objectId", accountBankOId);
    query.equalTo("userOId", uId);
    query.first().then(accountBankObj=>{
      return callback(accountBankObj);
    }).catch(error=>{
      console.log('getUserBankObj',error)
      return callback(null);
    })
  }
}

/**
 * 执行提现
 * @param shopAccountObj 用户虚拟账户
 * @param money 提现金额
 * @param callback
 */
function doWithdraw(shopAccountObj, money, bankObj, callback) {
  var state = 0;
  var msg = "";
  var ShopAccountDetail = common.getEntity("Shop_account_detail");
  var shopAccountDetail = new ShopAccountDetail();
  shopAccountDetail.set("userOId", shopAccountObj.get("userOId"));
  shopAccountDetail.set("userObj", {
    "__type": "Pointer",
    className: "_User",
    objectId: shopAccountObj.get("userOId")
  });
  shopAccountDetail.set("changeMoney", common.formatMoney(money));//提现金额
  shopAccountDetail.set("procedureRate", apis["Withdrawal"]["rate"]);//提现手续费比率
  shopAccountDetail.set("procedureFee", common.formatMoney(shopAccountDetail.get("changeMoney") * apis["Withdrawal"]["rate"]));//提现手续费
  shopAccountDetail.set("changeType", "3");
  shopAccountDetail.set("bankName", bankObj.get("bankName"));
  shopAccountDetail.set("bankNo", bankObj.get("bankNo"));
  shopAccountDetail.set("name", bankObj.get("name"));
  shopAccountDetail.set("remark", "提现中，请等待(已扣除手续费" + shopAccountDetail.get('procedureFee') + "元)");
  shopAccountDetail.set("withdrawStatus", "0");//提现中
  //是否查看过
  shopAccountDetail.set("isLook", "0");
  shopAccountDetail.save().then(newShopAccountDetail =>{
    //更新总账户
    // shopAccountObj.fetchWhenSave(true);
    shopAccountObj.increment("withdrawFrozenMoney", money);
    shopAccountObj.save({fetchWhenSave:true}).then(newShopAccountObj =>{
      state = 1;
      msg = "申请提现成功，请等待人工审核！";
      return callback(state, msg)
    }).catch(err=>{
      console.log('doWithdraw-Err:',err)
      msg = err.message;
      //如果账户信息更新错误，则删除账户变动明细
      newShopAccountDetail.destroy();
      return callback(state, msg)
    })
  }).catch(error=>{
    console.log('doWithdraw-Error:',error)
    msg = error.message;
    return callback(state, msg)
  })
}

//获取地区列表
router.post('/getRegionListFromDictionary', function (req, res) {
  let fatherCode = req.body.fatherCode
  if (!fatherCode){
    fatherCode = '0'
  }
  let query = new AV.Query('Dictionary')
  query.equalTo("type", '1');
  query.equalTo("fatherCode", fatherCode);
  query.descending('sortNum')
  query.find().then(provinceObjs=>{
    let data = []
    provinceObjs.map(item=>{
      let tempObj = {
        label:item.get('name'),
        value:item.get('code'),
        key:item.id
      }
      data.push(tempObj)
    })
    res.json(common.getReturnArr("OK", "10000", "地区列表获取成功！", data));
  }).catch(error=>{
    console.log('getRegionListFromDictionary',error)
    res.json(common.getErrArr(error.msg));
  })
})

//获取运费模板列表
router.post('/getPostageModelList', async function (req, res) {
  var shopInfo = await getShopInfo(req.currentUser.id)
  let shopOId = shopInfo.shopOId
  let page = req.body.page;
  let num = req.body.num;
  let objectId = req.body.postageModelOId;
  let name = req.body.postageModelName;
  let status = req.body.postageModelStatus;
  if (page == '' || page == undefined || page == null) {
    page = 1;
  } else {
    page = parseInt(page);
  }
  if (num == '' || num == undefined || num == null) {
    num = 10
  } else {
    num = parseInt(num)
  }
  var query = new AV.Query('PostageModel');

  if (shopOId != "" && shopOId != undefined && shopOId != null) {
    query.equalTo("shopOId", shopOId);
  }
  if (objectId != "" && objectId != undefined && objectId != null) {
    query.equalTo("objectId", objectId);
  }
  if (name != "" && name != undefined && name != null) {
    query.contains("name", name);
  }
  // if (status != "" && status != undefined && status != null) {
  //   query.equalTo("status", Number(status));
  // } else {
  //   if (!objectId){
  //     query.equalTo("status", 0);
  //   }
  // }
  query.equalTo("status", 0);
  query.skip((page - 1) * num);
  query.limit(num);
  query.include('shopObj');
  query.descending('createdAt');
  query.find().then(function (result) {
      query.count().then(async function (count) {
        var obj = {};
        var data = [];
        for (let i = 0; i < result.length; i++) {
          var temObj = {};
          temObj["objectId"] = result[i].get("objectId");
          temObj["shopOId"] = result[i].get("shopOId");//店铺Id
          temObj["name"] = result[i].get("name");//模板名称
          temObj["isFree"] = result[i].get("isFree");//是否包邮1包邮0不包
          temObj["billingType"] = result[i].get("billingType");//计费方式
          temObj["firstWeight"] = result[i].get("firstWeight");//首重/件
          temObj["firstPostage"] = result[i].get("firstPostage");//首费
          temObj["moreWeight"] = result[i].get("moreWeight");//续重/件
          temObj["morePostage"] = result[i].get("morePostage");//续费
          temObj["freeCondition"] = result[i].get("freeCondition");//包邮条件0价格1重量
          temObj["conditionValue"] = result[i].get("conditionValue");//满多少包邮
          temObj["selfSupportingRegion"] = result[i].get("selfSupportingRegion");//买家自费区域
          temObj["notDeliveryRegion"] = result[i].get("notDeliveryRegion");//不配送区域
          temObj["isFreeCondition"] = result[i].get("isFreeCondition");//是否指定包邮条件1指定0未指定
          temObj["status"] = result[i].get("status");
          temObj["createdAt"] = moment(result[i].createdAt).format('YYYY年MM月DD日 HH:mm:ss');
          temObj["updatedAt"] = moment(result[i].updatedAt).format('YYYY年MM月DD日 HH:mm:ss');
          data.push(temObj);
        }
        obj.data = data;
        obj.total = count;
        obj.shopInfo = shopInfo;

        res.json(common.getReturnArr("OK", "10000", "运费模板列表获取成功！", obj));
      }).catch(err => {
        console.log(err);
      })
    }, function (error) {
      console.log(error);
      res.json(common.getErrArr(error.msg));
    }
  )
})
//添加及编辑运费模板信息
router.post('/postageModelUpdate', function (req, res) {
  // console.log(req.body)
  let objectId = req.body.objectId
  let shopOId = req.body.shopOId
  let name = req.body.name //模板名称
  let isFree = req.body.isFree //是否包邮1包邮0不包
  let billingType = req.body.billingType //计费方式
  let firstWeight = req.body.firstWeight //首重/件
  let firstPostage = req.body.firstPostage //首费
  let moreWeight = req.body.moreWeight //续重/件
  let morePostage = req.body.morePostage //续费
  let isFreeCondition = req.body.isFreeCondition //是否指定包邮条件
  let freeCondition = req.body.freeCondition //包邮条件0价格1重量
  let conditionValue = req.body.conditionValue //满多少包邮
  let selfSupportingRegion = req.body.selfSupportingRegion //买家自费区域
  let notDeliveryRegion = req.body.notDeliveryRegion //不配送区域

  if (objectId != "" && objectId != undefined && objectId != null) {
    var postageModel = AV.Object.createWithoutData('PostageModel', objectId);
  } else {
    let PostageModel = AV.Object.extend("PostageModel");
    var postageModel = new PostageModel();
    var shopObj = AV.Object.createWithoutData('Shop_shop',shopOId);
    postageModel.set("status",0);
  }
  postageModel.set("name", name);
  postageModel.set("isFree", Number(isFree));
  postageModel.set("billingType", Number(billingType));
  postageModel.set("firstWeight", Number(firstWeight));
  postageModel.set("firstPostage", Number(firstPostage));
  postageModel.set("moreWeight", Number(moreWeight));
  postageModel.set("morePostage", Number(morePostage));
  postageModel.set("selfSupportingRegion", selfSupportingRegion);
  postageModel.set("notDeliveryRegion", notDeliveryRegion);
  if (isFreeCondition == 'true'){
    postageModel.set("isFreeCondition", 1);
    postageModel.set("freeCondition", Number(freeCondition));
    postageModel.set("conditionValue", Number(conditionValue));
  } else {
    postageModel.set("isFreeCondition", 0);
    postageModel.unset("freeCondition");
    postageModel.unset("conditionValue");
  }
  postageModel.set("shopOId",shopOId);
  postageModel.set("shopObj",shopObj);
  postageModel.save().then(postageModelObj=>{
    res.json(common.getReturnArr("OK", "10000", "更新运费模板成功！", postageModelObj.id));
  }).catch(error=>{
    console.log('postageModelUpdate',error)
    res.json(common.getErrArr(error.msg));
  })
})

//运费模板删除
router.post('/postageModelDel', function (req, res) {
  let objectId = req.body.objectId
  if (objectId != "" && objectId != undefined && objectId != null) {
    var ostageModelObj = AV.Object.createWithoutData("PostageModel", objectId)
    ostageModelObj.set('status', -1);
    ostageModelObj.save().then(model=>{
      res.json(common.getReturnArr("OK", "10000", "商品删除成功！", model.id));
    }).catch(error=>{
      console.log('shopGoodsDelError',error)
      res.json(common.getErrArr(error.msg));
    })
  } else  {
    res.json(common.getErrArr('请传入模板ID！'));
  }
})
//运费模板列表关联商品
router.post('/getPostageModelListForGoods', async function (req, res) {
  var shopInfo = await getShopInfo(req.currentUser.id)
  let shopOId = shopInfo.shopOId
  // if (shopOId != shopInfo.shopOId){
  //   res.json(common.getErrArr('传入店铺ID与登录用户店铺ID不符！'));
  // }
  // console.log(shopOId,shopInfo.shopOId)
  var query = new AV.Query('PostageModel');
  query.equalTo("status", 0);
  query.equalTo("shopOId", shopOId);
  query.include('shopObj');
  query.descending('createdAt');
  query.find().then(function (result) {
    var data = [];
    for (let i = 0; i < result.length; i++) {
      var temObj = {};
      temObj["value"] = result[i].get("objectId");
      temObj["label"] = result[i].get("name");//模板名称
      data.push(temObj);
    }
    res.json(common.getReturnArr("OK", "10000", "运费模板列表获取成功！", data));
    }, function (error) {
      console.log(error);
      res.json(common.getErrArr(error.msg));
    }
  )
})
//批量修改商品运费模板
router.post('/changeGoodsRelationPostageModelForBatch', function (req, res) {
  let goodsOIdsArr = req.body.goodsOIdsArr
  let postageModelOId = req.body.postageModelOId
  let goods = new AV.Query('Shop_goods');
  goods.containedIn("objectId", goodsOIdsArr);
  goods.find().then(goodsObjs => {
    goodsObjs.forEach(item => {
      item.set("postageModelOId", postageModelOId);
      let postageModelObj = AV.Object.createWithoutData('PostageModel', postageModelOId);
      item.set('postageModelObj', postageModelObj);
    })
    AV.Object.saveAll(goodsObjs).then(result=>{
      res.json(common.getReturnArr("OK", "10000", "商品批量修改运费模板成功！", result));
    }).catch(error=>{
          console.log('changeGoodsRelationPostageModelForBatch',error)
          res.json(common.getErrArr(error.msg));
    })
  })



  // if (objectId != "" && objectId != undefined && objectId != null) {
  //   var ostageModelObj = AV.Object.createWithoutData("PostageModel", objectId)
  //   ostageModelObj.set('status', -1);
  //   ostageModelObj.save().then(model=>{
  //     res.json(common.getReturnArr("OK", "10000", "商品删除成功！", model.id));
  //   }).catch(error=>{
  //     console.log('shopGoodsDelError',error)
  //     res.json(common.getErrArr(error.msg));
  //   })
  // } else  {
  //   res.json(common.getErrArr('请传入模板ID！'));
  // }
})

module.exports = router;